<template>
  <el-drawer v-model="dialogVisible" :show-close="false" :close-on-click-modal="false" >
    <template #header>
        <div class="btns routeHeader mb-5px" ref="topBoxRef">
      <el-button
        type="primary"
        @click="submitForm('commit')"
        :loading="formLoading"
        v-hasPermi="['quality:mgmt-defective-product-registration:commit']"
        v-if="formData.dictExceptionRegistrationStatus==20 && !viewStatus"
      >
        提交
      </el-button>
      <el-button @click="cancelForm"> 关闭 </el-button>
    </div>
    </template>
    <div v-loading="formLoading" class="bg">
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="100px"
      v-loading="formLoading"
    >
    <el-form-item label="检验类型" prop="dictInspectType">
        <el-select 
        v-model="formData.dictInspectType" 
        placeholder="请选择检验类型"
        :disabled="formData.dictExceptionRegistrationStatus!=20 || viewStatus " >
          <el-option
            v-for="dict in getIntDictOptions('dict_inspect_type')"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="检验任务号" prop="checkTaskNumber">
        <el-input v-model="formData.checkTaskNumber" placeholder="" disabled />
      </el-form-item>
      <el-form-item label="产品编号" prop="productNumber">
        <el-input v-model="formData.productNumber" placeholder="" disabled />
      </el-form-item>
      <el-form-item label="部件编号" prop="partNumber">
        <el-input v-model="formData.partNumber" placeholder="请输入部件编号" disabled>
          <template #append>
            <el-button :icon="Search" @click="openPartNumberForm()"/>
          </template>
          </el-input>
      </el-form-item>
      <el-form-item label="部件名称" prop="partName">
        <el-input v-model="formData.partName" placeholder="" disabled/>
      </el-form-item>
      <el-form-item label="图纸图号" prop="drawingNumber">
        <el-input v-model="formData.drawingNumber" placeholder="" disabled/>
      </el-form-item>
      <el-form-item label="异常数量" prop="exceptionQuantity" >
        <el-input 
        v-model="formData.exceptionQuantity" 
        placeholder="请输入异常数量" 
        disabled/>
      </el-form-item>
      <!--字段 -->
      <el-form-item label="客户名称" prop="customerName">
        <el-input v-model="formData.customerName" placeholder="" disabled/>
      </el-form-item>
      <!--  -->
      <el-form-item label="单位" prop="partUnit">
        <el-input v-model="formData.partUnit" placeholder="" disabled/>
      </el-form-item>
      <el-form-item label="描述" prop="description">
        <el-input 
        v-model="formData.description" 
        type="textarea" 
        placeholder="请输入描述"
        maxlength="200" 
        show-word-limit
        style="width:500px"
        disabled/>
      </el-form-item>
      <el-form-item label="最终结论" prop="dictFinalConclusion">
        <el-select 
        v-model="formData.dictFinalConclusion" 
        placeholder="" 
        :disabled="formData.dictExceptionRegistrationStatus!=20 || viewStatus ">
          <el-option
            v-for="dict in getIntDictOptions('dict_final_conclusion')"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="检验说明" prop="inspectionNotes">
        <el-input 
        v-model="formData.inspectionNotes" 
        type="textarea" 
        placeholder=""
        maxlength="200" 
        show-word-limit
        style="width:500px"
        :disabled="formData.dictExceptionRegistrationStatus!=20 || viewStatus "
        />
      </el-form-item>
      <el-form-item label="附件上传" prop="fileId" v-if="!viewStatus">
          <UploadFile
            v-model="fileList"
            :limit="1"
            :fileSize="200"
            :fileType="['pdf', 'png', 'jpg']"
            @update:modelValue="uploadFileRes"
          />
        </el-form-item>
        <el-form-item label="附件名称" prop="fileName" v-else>
          <el-button v-if="formData.fileName" type="primary" @click="openFile(formData.filePath)">{{
            formData.fileName
          }}</el-button>
        </el-form-item>

    </el-form>
  </div>
    <!-- 上传文件 -->
  <CusUploadFile ref="cusUploadFile" @refresh="getDrawingList" :onlyUpdate="false" />
</el-drawer>
</template>
<script setup>
import { getIntDictOptions } from '@/utils/dict'
import * as MgmtDefectiveProductDeterminationApi from '@/api/quality/qualitycontrol/MgmtDefectiveProductDetermination'
import { Search } from '@element-plus/icons-vue'
const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗
const dialogVisible = ref(false) // 弹窗的是否展示
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formData = ref({})
const topBoxRef = ref()
const formRules = reactive({
  dictFinalConclusion: [{ required: true, message: '最终结论不能为空', trigger: 'change' }],
  inspectionNotes: [{ required: true, message: '检验说明不能为空', trigger: 'blur' }],
})
const list =ref({})

const formRef = ref() // 表单 Ref
const fileList = ref([])//附件上传

/**文件上传返回 */
const uploadFileRes = async(data) => {
  if (JSON.parse(data).length) {
    const res = JSON.parse(data)
    formData.value.fileName = res[0].name
    formData.value.filePath = res[0].url
  } else {
    fileList.value = []
    formData.value.fileName = ''
    formData.value.filePath = ''
  }
}

// 查看文件
const openFile = (path) => {
  if (!path) {
    message.notifyError('附件不存在!')
    return
  }
  window.open(path)
}

const viewStatus = ref(false) //查看状态
// /** 打开弹窗 */
const rowId = ref()
const formType = ref()
const open = async (type,id) => {
  formType.value = type
  rowId.value = id
  dialogVisible.value = true
  getList()
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗

const getList = async() =>{
  formLoading.value = true
  try{
    if(rowId.value){
    formData.value = await MgmtDefectiveProductDeterminationApi.getMgmtDefectiveProductDetermination(rowId.value )
    if(formData.value.fileName !=null){
      // fileList.value=[]
      if(fileList.value.length==0){
        fileList.value.push({
        name:formData.value.fileName,
        url:formData.value.filePath,
      })
      }
    } 
  }
  if(formType.value=='view'){
    viewStatus.value = true
  }else{
    viewStatus.value = false
  }}
  finally{
    formLoading.value = false
  }
}

//关闭
const cancelForm = () =>{
  dialogVisible.value = false
}
const emit = defineEmits(['success'])
/** 提交表单 */
const submitForm = async (type) => {
  // 校验表单
  if (!formRef) return
  const valid = await formRef.value.validate()
  if (!valid) return
  // 提交请求
  formLoading.value = true
  formData.value.exceptionQuantity = Number(formData.value.exceptionQuantity)
  try {
    //保存
    if(type=='commit'){
      if(formData.value.dictExceptionRegistrationStatus!=10){
      list.value.id =Number(rowId.value)
      list.value.dictExceptionRegistrationStatus = 30
      list.value.dictInspectType=formData.value.dictInspectType
      list.value.inspectionNotes=formData.value.inspectionNotes
      list.value.dictFinalConclusion=formData.value.dictFinalConclusion
      list.value.fileName=formData.value.fileName
      list.value.filePath=formData.value.filePath
      await MgmtDefectiveProductDeterminationApi.updateMgmtDefectiveProductDetermination(list.value)
      message.success(t('提交成功'))
      }else{
      message.warning(t('数据已被撤回'))
      }
    }
    dialogVisible.value = false
    emit('success')
  } finally {
    formLoading.value = false
  }
}


/** 初始化 **/
// onMounted(async () => {
//   await getList()
// })
</script>

<style lang="scss" scoped>
.bg{
  background-color:white;
}

// ::v-deep .el-drawer__header{
//   margin-bottom:0px !important;
// }
</style>
